import grok
from persistent.dict import PersistentDict

class FinancialHistory(grok.Application, grok.Container):
    def __init__(self, initialBalance=0):
        super(FinancialHistory, self).__init__()
        self.cashOnHand = initialBalance
        self.incomes = PersistentDict()      # 
        self.expenditures = PersistentDict() #

    def receiveFrom(self, source, amount):
        self.incomes[source] = self.totalReceivedFrom(source) + amount
        self.cashOnHand += amount
        
    def spendFor(self, reason, amount):
        self.expenditures[reason] = self.totalSpentFor(reason) + amount
        self.cashOnHand -= amount
        
    def totalReceivedFrom(self, source):
        return self.incomes.get(source, 0)
    
    def totalSpentFor(self, reason):
        return self.expenditures.get(reason, 0)


class Index(grok.View):
    def cashOnHand(self):
        return '%0.2f' % (self.context.cashOnHand)

    def update(self, source=None, amount=None):
        if source is not None:
            self.context.receiveFrom(source,float(amount))

    def listIncome(self):
        return [{'source':k, 'amount': '%0.2f'%v} 
            for k,v in self.context.incomes.items()]
